<?php

class Core_Component_Account_Controller_Backend_Account {
    
    public function __construct() {
        $GLOBALS[RC]->getHelper()->setLocation('{account.account}', '{account.account_index}');
    }
    
    public function mappingAction(){
        return array(
            'create'=>'edit'
        );
    }

    public function indexAction($pageindex = 1, $pagesize = 20, $sort = 'user_name', $dir = 'asc') {
        $q = App::getModel('account/account')->getQuery();
        $list = $q->orderby($sort, $dir)->pagination($pageindex, $pagesize)->fetch();
        $count = $q->fetchCount();
        return $GLOBALS[RC]->getHelper()->templateResult(array('list' => $list, 'record_count' => $count));
    }

    public function editAction($id = NULL) {
        $h = $GLOBALS[RC]->getHelper();
        $model = App::getModel('account/account');
        $actions = App::getModel('account/action')->getQuery()->fetch();
        $roles = App::getModel('account/role')->getQuery()->fetch();
        if (empty($id)) {
            $h->setLocation('{account.account_create}');
        } else {
            $model->load($id);
            $h->setLocation($model->getUserName());
        }
        return $GLOBALS[RC]->getHelper()->modelFormResult(
                $model,
                array(
                    'action_codes' => array('data'=>$actions, 'labelKey'=>'name', 'valueKey'=>'code'),
                    'role_codes' => array('data' => $roles, 'labelKey'=>'name', 'valueKey'=>'code')
                ),
                '*/*/edit');
    }

    public function savePostAction(Core_Component_Account_Model_Account $model) {
        try {
            if (!$model->getIdValue()) {
                $model->setPassword(md5($model->getPassword()));
            }
            $model->merge()->validate()->save();
            $GLOBALS[RC]->getMessager()->addSuccess('{system.message.success}');
            return $GLOBALS[RC]->getHelper()->redirectResult('*/*/*/index');
        } catch (Core_Component_Account_Exception $ex) {
            $GLOBALS[RC]->getHelper()->setLocation('{account.role_index}', '{account.role_create}');
            if ($ex->getMessage() == Core_Component_Account_Exception::ACCOUNT_REPEATED) {
                $GLOBALS[RC]->getMessager()->addError('account.'.$ex->getMessage());
            }
            return backend_user_account_edit()->setModel($model);
        }
    }

    public function deleteAction($ids) {
        App::getModel('account/account')->deleteBatch($ids);
        $GLOBALS[RC]->getMessager()->addSuccess('{system.message.success}');
        return $GLOBALS[RC]->getHelper()->redirectResult('*/*/*/index');
    }
}